package inftel.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.UUID;





/*
import dk.itu.android.bluetooth.BluetoothAdapter;
import dk.itu.android.bluetooth.BluetoothDevice;
import dk.itu.android.bluetooth.BluetoothServerSocket;
import dk.itu.android.bluetooth.BluetoothSocket;
*/

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class BluetoothConnectionActivity extends Activity 
{
	static final int REQUEST_ENABLE_DISCOVERABLE = 2;
	static final int REQUEST_CONNECT_DEVICE = 3;

	private UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
	BluetoothAdapter btAdapter;
	BluetoothSocket socket;
	//Server server;
	//Client client;
	TextView responseTextView;//=(TextView)findViewById(R.id.response_text_view);
	String mac;
	Button connect;
	/*
	private class Server implements Runnable 
	{
	    boolean running = true;
	    BluetoothServerSocket socket = null;

	    public void stop()
	    {
	        running = false;
	        if(socket != null)
	        {
	            try
	            {
	            	socket.close();
	            	socket=null;
	            }
	            catch(Exception ignored){}
	        }
	    }

	    public void run()
	    {
	        try 
	        {
				socket = btAdapter.listenUsingRfcommWithServiceRecord("Bluetooth_Service", uuid);

	        }
	        catch (IOException e)
	        {
				// TODO Auto-generated catch block
				e.printStackTrace();
				running = false;
			}
			while(running)
			{
				BluetoothSocket clientSocket = null;
				try 
				{
					clientSocket = socket.accept();
					BufferedReader bufReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			        final String line = bufReader.readLine().trim();
			        clientSocket.getOutputStream().write( (">"+line+"\r\n").getBytes("UTF-8") );
			        clientSocket.getOutputStream().flush();
			        runOnUiThread(new Runnable()
			        {
			            @Override
			            public void run() {
			                appendToResponseView("Received >> "+line);
			            }
			        });
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				finally 
				{
			        if(clientSocket != null) 
			        {
			            try{clientSocket.close();}catch(Exception ignored){}
			        }
			    }
			}
	    }

		protected void appendToResponseView(String line) {
			// TODO Auto-generated method stub
			String curText = responseTextView.getText().toString();
		    if(curText.length()!=0) {
		        curText+="\n";
		    }
		    curText+=line;
		    responseTextView.setText(curText);
		}
	}
	
	private class Client implements Runnable {
	    BluetoothDevice device;
	    BluetoothSocket socket;
	    String message="Hola";
	    public Client(){
	        device = btAdapter.getRemoteDevice(mac);
	    }

	    public void run(){
	    	
	    	try {
				socket = device.createRfcommSocketToServiceRecord(uuid);
				socket.connect();
				socket.getOutputStream().write( (message+"\r\n").getBytes("UTF-8") );
			    socket.getOutputStream().flush();
			    BufferedReader bufReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			    final String echoed = bufReader.readLine();
	            appendToResponseView("Received >> "+ echoed);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			finally 
			{
		        if(socket != null) 
		        {
		            try{socket.close();}catch(Exception ignored){}
		        }
		    }
	    }
	    
	    protected void appendToResponseView(String line) {
			// TODO Auto-generated method stub
			String curText = responseTextView.getText().toString();
		    if(curText.length()!=0) {
		        curText+="\n";
		    }
		    curText+=line;
		    responseTextView.setText(curText);
		}
	    
	}
	*/
	private ProgressDialog  btTaskDialog;
	

	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        setContentView(R.layout.establish_connection);
        
        Bundle bundle = getIntent().getExtras();
		mac = bundle.getString("MAC");
		
		//server=new Server();
		TextView tv = (TextView) findViewById(R.id.selected_device_mac);
		tv.setText("Selected MAC: "+mac);
		    btTaskDialog = new ProgressDialog(this);
	        btTaskDialog.setMessage("Bluetooth Server Task...");
	        btTaskDialog.setTitle("Progress");
	        btTaskDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	        btTaskDialog.setCancelable(false);
		//new Thread(server).start();
		//new Thread(client).start();
   	 	btAdapter = BluetoothAdapter.getDefaultAdapter();
   	 	btAdapter.startDiscovery();
		//startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE),REQUEST_ENABLE_DISCOVERABLE);
		establishBluetoothConnection(mac);
		//startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE),REQUEST_CONNECT_DEVICE);

		
		/*
		if(socket!=null)
		{
	    	  Toast.makeText(this, "socket!=null", Toast.LENGTH_LONG).show();	
	
		}
		else
		{
	    	  Toast.makeText(this, "socket==null", Toast.LENGTH_LONG).show();	

		}
		//sendMessage(socket, "Hello Bluetooth");

		*/

	}
	
	
	private void establishBluetoothConnection(final String macAddress)
	{
		connect=(Button) findViewById(R.id.connect);
		// TODO Auto-generated method stub
		View.OnClickListener connectListener = new OnClickListener() 
	    {
	        public void onClick(View v) 
	        {    	
	        	  AsyncTask<Integer, Void, Void> connectTask = 
	                  new AsyncTask<Integer, Void, Void>() { 
	                    @Override
	                    protected Void doInBackground(Integer... params) {
	                    	
	                      try {
	                        BluetoothDevice device = btAdapter.getRemoteDevice(macAddress);
	                        
	                        BluetoothSocket btSocket = device.createRfcommSocketToServiceRecord(uuid);
	                        if(btSocket==null){finish();}
	                        else{
	                        btSocket.connect(); 
	                        sendMessage(btSocket, "Hello Bluetooth");
	                        }

	                        
	                      } catch (IOException e) {
	                        Log.d("BLUETOOTH_CLIENT", e.getMessage());
	                      }
	                      return null;
	                    }

	                    @Override
	                    protected void onPostExecute(Void result) {
	                      switchUI();
	                      
	                    }
	                  };
	                connectTask.execute();
	                
	                
	              }      	
	        
	        
	    };
		connect.setOnClickListener(connectListener);

		
		
	}


	@Override
	  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (requestCode == REQUEST_ENABLE_DISCOVERABLE) {
	        String name = "bluetoothserver";
	        try {
		      Toast.makeText(this, "Bluetooth is discoverable", Toast.LENGTH_LONG).show();	
	          Toast.makeText(this, "call 2 listenUsingRfcommWithServiceRecord", Toast.LENGTH_LONG).show();	
		      final BluetoothServerSocket btserver = 
	            btAdapter.listenUsingRfcommWithServiceRecord(name, uuid);
	          	if(btserver!=null){
	  		      Toast.makeText(this, "btserver!=null", Toast.LENGTH_LONG).show();		
	          	}


	          AsyncTask<Integer, Integer, BluetoothSocket> acceptThread = 
	            new AsyncTask<Integer, Integer, BluetoothSocket>() {
	        	
	        	  @Override
				 	protected void onPreExecute() 
				 	{
				 		super.onPreExecute();
				 		btTaskDialog.setProgress(0);
				 		btTaskDialog.setMax(100);
				 		btTaskDialog.show(); 
				 	}
	        	  
	        	  protected void onProgressUpdate (Integer... valores) 
				 	 {
				 		 btTaskDialog.setProgress(valores[0]);
				 	 }

	            @Override
	            protected BluetoothSocket doInBackground(Integer... params) {
	            	publishProgress(25); 
	              try {
	            	  publishProgress(50); 
	                socket = btserver.accept(params[0]*1000);
	                publishProgress(75); 
	                return socket;
	              } catch (IOException e) {
	                Log.d("BLUETOOTH", e.getMessage());            
	              }
	              return null;
	            }

	            @Override
	            protected void onPostExecute(BluetoothSocket result) {
	              if (result != null)
	            	  publishProgress(100); 
	            	  switchUI();
	            }            
	          };          
	          acceptThread.execute(resultCode);
	        } catch (IOException e) {
	          Log.d("BLUETOOTH", e.getMessage());            
	        }
	      }
	      else if (requestCode == REQUEST_CONNECT_DEVICE)
	      {
	    	  Toast.makeText(this, "REQUEST_CONNECT_DEVICE", Toast.LENGTH_LONG).show();	
	    	  
	    	  AsyncTask<Integer, Void, Void> connectTask = 
	              new AsyncTask<Integer, Void, Void>() { 
	                @Override
	                protected Void doInBackground(Integer... params) {
	                  try {
	                    BluetoothDevice device = btAdapter.getRemoteDevice(mac);
	                    socket = device.createRfcommSocketToServiceRecord(uuid);
	                    
	                    socket.connect();              
	                  } catch (IOException e) {
	                    Log.d("BLUETOOTH_CLIENT", e.getMessage());
	                  }
	                  return null;
	                }

	                @Override
	                protected void onPostExecute(Void result) {
	                  switchUI();
	                }
	              };
	      
	      }
	    }
	  

	
	
	
		
	

	@Override
	protected void onStart() 
	{
		// TODO Auto-generated method stub
		super.onStart();
	}
	
	private void switchUI() 
	{
		final TextView messageText = (TextView)findViewById(R.id.text_message_rx);
		final EditText textEntry = (EditText)findViewById(R.id.text_message_tx);
		messageText.setVisibility(View.VISIBLE);
		textEntry.setEnabled(true);
		
	}
	
	private void sendMessage(BluetoothSocket socket, String msg) {
	    OutputStream outStream;
  	 // Toast.makeText(this, "Envio el mensaje", Toast.LENGTH_LONG).show();	
	    finish();
	    try {
	      outStream = socket.getOutputStream();
	      byte[] byteString = (msg + " ").getBytes();
	      byteString[byteString.length - 1] = 0;
	      outStream.write(byteString);

	    } catch (IOException e) {
	      Log.d("BLUETOOTH_COMMS", e.getMessage());
	    }    
	  }
	
	
	
}






/* 



 

*/
